﻿class Solution {
public:
    struct kvCompare
    {
        bool operator()(const pair<string, int>& p1, const pair<string, int>& p2)
        {
            return p1.second > p2.second;
        }
    }

    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string, int> countMap;
        for (auto e : words)
        {
            countMap[e]++;
        }
        vector<pair<string, int>> v(countMap.begin(), countMap.end());
        // 仿函数控制降序
        stable_sort(v.begin(), v.end(), kvCompare());//稳定排序，不改变相等值相对位置
        // 取前k个
        vector<string> strV;
        for (int i = 0; i < k; ++i)
        {
            strV.push_back(v[i].first);
        }

        return strV;
    }
};